package org.springblade.modules.sga.controller;

import com.wfl.uias.common.JsonUtils;
import com.wfl.uias.dto.JITUser;
import org.springblade.common.cache.CacheNames;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.RedisUtil;
import org.springblade.modules.enterprise.service.IEnterpriseService;
import org.springblade.modules.enterprise.vo.EnterpriseVO;
import org.springblade.modules.sga.service.ISgaUiasService;
import org.springblade.modules.sga.vo.SgaJITLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@Controller
public class SgaUiasController {

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private ISgaUiasService uiasService;

	@Autowired
	private IEnterpriseService enterpriseService;

	@Value("${uias.appCode}")
	private String appCode;

	@Value("${uias.loginPath}")
	private String loginPath;

	@Value("${uias.backPath}")
	private String backPath;

	@RequestMapping("")
	public void index(HttpServletResponse response) throws IOException {
		response.sendRedirect("uiasIndex.do");
	}

	@ResponseBody
	@RequestMapping("/uiasIndex.do")
	public R<String> uiasIndex(HttpServletRequest request) {
		//String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
		//System.out.println(basePath);
		return R.data(loginPath + "uias_login.do?appCode=" + appCode + "&&gotoUrl=");
	}

	@RequestMapping("/uiasBuss.do")
	public void uiasBuss(HttpServletRequest request, HttpServletResponse response) throws IOException {

		/**
		 * TODO: authType 因为目前参数没有详细文档，所以不合适用来做业务处理。
		 * 	_1_: 扫码登录
		 * 	_1_,_11_: 用户名密码登录
		 * 	...: 其他未知
		 */

		/* 获取用户信息 */
		JITUser jitUser = (JITUser) request.getSession().getAttribute("jitUser");
		System.out.println("8.jitUser=" + JsonUtils.beanToText(jitUser));

		/* 获取token */
		String accessToken = (String) request.getSession().getAttribute("access_token");
		/* 获取认证源 */
		String authSource = (String) request.getSession().getAttribute("authSource");
		/* 获取gotoUrl */
		String gotoUrl = (String) request.getSession().getAttribute("gotoUrl");
		System.out.println("9.gotoUrl=" + gotoUrl);
		/* 获取jitObject */
		SgaJITLoginVO loginVO = uiasService.GetJITLoginUser(accessToken);
		if (loginVO != null) {
			loginVO.setUserId(jitUser.getUserId());
			loginVO.setSessionId(jitUser.getSessionId());
			loginVO.setAccessToken(accessToken);
			loginVO.setAuthSource(authSource);
			loginVO.setGotoUrl(Func.isEmpty(gotoUrl) ? backPath : gotoUrl);

			switch (loginVO.getUserType()) {
				// 法人登录
				case 2:
					EnterpriseVO enterprise = enterpriseService.getEnterpriseByCode(loginVO.getUnitCode());
					if (enterprise == null) {
						loginVO.setEntUser(0);
					} else {
						if (Func.isEmpty(enterprise.getLegalCard()) || Func.isEmpty(enterprise.getMobilePhone())|| Func.isEmpty(enterprise.getLegalName())) {
							enterpriseService.updateFromJITObject(loginVO, enterprise.getId());
						}
					}
					break;
				// 个人登录
				default:
					break;
			}

			redisUtil.del(CacheNames.UIAS_AUTH_KEY.replace("{1}", jitUser.getSessionId()).replace("{0}", jitUser.getUserId()));
			redisUtil.set(CacheNames.UIAS_AUTH_KEY.replace("{1}", accessToken).replace("{0}", jitUser.getUserId()), JsonUtils.beanToText(loginVO), 24L, TimeUnit.HOURS);

			// Logout URL:
			// "https://oauth.hubei.gov.cn:8443/uias/uias/LogOut?sessionId=" + jitUser.getSessionId() + "&goBack=" + loginPath;

			response.sendRedirect(backPath + "?token=" + accessToken + "&random=" + jitUser.getUserId() + "&userType=" + loginVO.getUserType() + "&loginLevel=" + loginVO.getEntUser());
		} else {
			response.sendRedirect(backPath);
		}
	}

	@RequestMapping("uiasLogout.do")
	public void uiasLogout(@RequestParam("token") String token, @RequestParam("random") String random, @RequestParam(value = "sessionId", required = false) String sessionId, HttpServletResponse response) throws IOException {
		String redisKey = CacheNames.UIAS_AUTH_KEY.replace("{1}", token).replace("{0}", random);
		if (redisUtil.hasKey(redisKey)) {
			SgaJITLoginVO loginVO = JsonUtils.textToBean(new SgaJITLoginVO(), String.valueOf(redisUtil.get(redisKey)));
			redisUtil.del(redisKey);
			response.sendRedirect("https://oauth.hubei.gov.cn:8443/uias/uias/LogOut?sessionId=" + loginVO.getSessionId() + "&goBack=" + loginVO.getGotoUrl());
//			response.sendRedirect(backPath);
			return;
		}

		if (Func.isNotEmpty(sessionId)) {
			response.sendRedirect("https://oauth.hubei.gov.cn:8443/uias/uias/LogOut?sessionId=" + sessionId + "&goBack=" + backPath);
//			response.sendRedirect(backPath);
			return;
		}

		response.sendRedirect(backPath);
	}
}
